package com.qms.tubu.activity.account;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.qms.tubu.R;
import com.qms.tubu.activity.BaseActivity;
import com.qms.tubu.bean.AccountBean;
import com.qms.tubu.tools.SPHelper;
import com.qms.tubu.tools.UrlConfig;
import com.qms.tubu.widget.LoadLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Struct;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.utils.WechatClientNotExistException;
import tool.lib.TextFormTool;
import tool.lib.ToastTool;
import tool.lib.volley.ExErrorListener;
import tool.lib.volley.ExListener;
import tool.lib.volley.JsonRequest;
import tool.lib.volley.VolleyTool;

/**
 * Created by Mad on 2015/7/20.
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener,PlatformActionListener,TextWatcher{
    private EditText mUsernameEdit,mPasswordEdit;
    private FrameLayout mCommitBtn;
    private TextView mCommitText;
    private LoadLayout mLoad;
    private Handler mErrorHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==0)
            {
                AlertDialog.Builder builder=new AlertDialog.Builder(LoginActivity.this);
                builder.setMessage("你的手机上未安装微信客户端,是否去微信官网下载微信?");
                builder.setPositiveButton("去下载", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.wechat_official_url)));
                            startActivity(intent);
                        }catch (Exception e){
                            ToastTool.showToast("请安装浏览器后再试");
                        }

                    }
                });
                builder.setNegativeButton("再看看", null);
                builder.show();
            }
            else if(msg.what==1)
            {
                requestThirdLogin((AccountBean) msg.obj);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        getSupportActionBar().setTitle("登录");
        ShareSDK.removeCookieOnAuthorize(true);
        findView();
        initData();

    }
    private void findView()
    {
        mUsernameEdit= (EditText) this.findViewById(R.id.login_username_edit);
        mPasswordEdit= (EditText) this.findViewById(R.id.login_password_edit);
        mCommitBtn= (FrameLayout) this.findViewById(R.id.login_commit_btn);
        mCommitText= (TextView) this.findViewById(R.id.login_commit_text);
        mLoad= (LoadLayout) this.findViewById(R.id.load_layout);
    }
    private void initData()
    {
        this.findViewById(R.id.weixin_login_btn).setOnClickListener(this);
        this.findViewById(R.id.weibo_login_btn).setOnClickListener(this);
        this.findViewById(R.id.qq_login_btn).setOnClickListener(this);
        mCommitBtn.setOnClickListener(this);
        mUsernameEdit.addTextChangedListener(this);
        mPasswordEdit.addTextChangedListener(this);
        setCommitBtnEnabled(false);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.qq_login_btn:
                Platform qqPlatform=ShareSDK.getPlatform(this, QQ.NAME);
                qqPlatform.setPlatformActionListener(this);
                qqPlatform.showUser(null);
                break;
            case R.id.weixin_login_btn:
                Platform weixinPlatform=ShareSDK.getPlatform(this, Wechat.NAME);
                weixinPlatform.setPlatformActionListener(this);
                weixinPlatform.showUser(null);
                break;
            case R.id.weibo_login_btn:
                Platform weiboPlatform=ShareSDK.getPlatform(this, SinaWeibo.NAME);
                weiboPlatform.setPlatformActionListener(this);
                weiboPlatform.showUser(null);
                break;
            case R.id.login_commit_btn:
                requestLogin();
                break;
        }
    }
    private void requestLogin(){
        hideSoftKeyboard();
        mLoad.startLoad();
        JsonRequest request=new JsonRequest(UrlConfig.getUrl(R.string.account_login),new ExListener(){
            @Override
            public void onResponse(JSONObject object) {
                super.onResponse(object);
                if(verifyResult.getResult()==0)
                {
                    try {
                        AccountBean account= JSON.parseObject(object.getString("account"),AccountBean.class);
                        account.setLoginType(SPHelper.LOGIN_TYPE_NORMAL);
                        SPHelper.saveAccount(LoginActivity.this, account);
                        getTubuApplication().setAccount(account);
                        finish();
                        return;
                    } catch (JSONException e) {
                        verifyResult.setResult(PARSE_ERROR);
                    }
                }
                mLoad.finishLoad();
                ToastTool.showToast(verifyResult.getMsg());
            }
        },new ExErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                super.onErrorResponse(error);
                mLoad.finishLoad();
            }
        });
        request.put("phone",mUsernameEdit.getText().toString());
        request.put("password",mPasswordEdit.getText().toString());
        request.setTag(LoginActivity.class);
        VolleyTool.getInstance().add(request);
    }
    private void requestThirdLogin(final AccountBean thirdAccount)
    {
        mLoad.startLoad();
        JsonRequest request=new JsonRequest(UrlConfig.getUrl(R.string.account_third_login),new ExListener(){
            @Override
            public void onResponse(JSONObject object) {
                super.onResponse(object);
                mLoad.finishLoad();
                if(verifyResult.getResult()==0)
                {
                    try {
                        AccountBean account=JSON.parseObject(object.getString("account"),AccountBean.class);
                        account.setLoginType(thirdAccount.getLoginType());
                        SPHelper.saveAccount(LoginActivity.this,account);
                        getTubuApplication().setAccount(account);
                        finish();
                        return;
                    } catch (JSONException e) {
                        verifyResult.setResult(PARSE_ERROR);
                    }
                }
                ToastTool.showToast(verifyResult.getMsg());
            }
        },new ExErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                super.onErrorResponse(error);
                mLoad.finishLoad();
            }
        });
        request.put("unionid",thirdAccount.getId());
        request.put("sex",String.valueOf(thirdAccount.getSex()));
        request.put("nickname",thirdAccount.getNickname());
        request.put("headimgurl",thirdAccount.getHeadimgurl());
        request.put("city",thirdAccount.getCity());
        request.put("province",thirdAccount.getProvince());
        request.put("type",thirdAccount.getLoginType());
        request.setTag(LoginActivity.class);
        VolleyTool.getInstance().add(request);
    }
    private void setCommitBtnEnabled(boolean enabled)
    {
        mCommitBtn.setEnabled(enabled);
        mCommitText.setEnabled(enabled);
    }
    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        AccountBean account=new AccountBean();
        if(platform instanceof QQ)
        {
            account.setId((String) hashMap.get("figureurl_qq_2"));
            account.setHeadimgurl((String) hashMap.get("figureurl_qq_2"));
            String sexStr= (String) hashMap.get("gender");
            account.setSex(sexStr.equals("男") ? 1 : 2);
            account.setNickname((String) hashMap.get("nickname"));
            account.setLoginType("qq");
            account.setCity((String) hashMap.get("city"));
            account.setProvince((String) hashMap.get("province"));

        }
        if(platform instanceof Wechat)
        {
            account.setId((String) hashMap.get("unionid"));
            account.setNickname((String) hashMap.get("nickname"));
            account.setCity((String) hashMap.get("city"));
            account.setProvince((String) hashMap.get("province"));
            account.setHeadimgurl((String) hashMap.get("headimgurl"));
            account.setSex((Integer) hashMap.get("sex"));
            account.setLoginType("wx");
        }
        if(platform instanceof SinaWeibo)
        {
            account.setId((String) hashMap.get("idstr"));
            account.setNickname((String) hashMap.get("name"));
            String[] location= ((String) hashMap.get("location")).split(" ");
            account.setCity(location[1]);
            account.setProvince(location[0]);
            account.setHeadimgurl((String) hashMap.get("avatar_large"));
            String sexStr= (String) hashMap.get("gender");
            account.setSex(sexStr.equals("m")?1:2);
            account.setLoginType("wb");
        }
        Message message=new Message();
        message.what=1;
        message.obj=account;
        mErrorHandler.sendMessage(message);
    }

    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        if(throwable instanceof WechatClientNotExistException)
        {
            mErrorHandler.sendEmptyMessage(0);
        }

    }

    @Override
    public void onCancel(Platform platform, int i) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        boolean canCommit=true;
        if(!TextFormTool.checkPhoneForm(mUsernameEdit.getText().toString()))
        {
            canCommit=false;
        }
        String passwordStr=mPasswordEdit.getText().toString();
        if(passwordStr.length()<6 || passwordStr.length()>16)
            canCommit=false;
        setCommitBtnEnabled(canCommit);
    }
}
